import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_book/api/api.dart';
import 'package:flutter_book/config/config.dart';
import 'package:flutter_book/data/model/resources_description_model.dart';
import 'package:flutter_book/util/extensions/string_extensions.dart';

class BackstageApi {
  static BackstageApi? _api;

  static BackstageApi init() {
    if(_api==null){
      _api = BackstageApi();
    }
    _api!._url = AppConfig.backstageApiUrl;
    return _api!;
  }

  String _url = "";

  //查询所有的表格的说明
  String _selectAllDescription = "/description/selectAllDescription";

  //查询所有的表格的说明
  Future<List<ResourcesDescriptionModel>?> selectAllDescription() async {
    Map<String, dynamic> params = {};
    try {
      List<ResourcesDescriptionModel> descriptionList = <ResourcesDescriptionModel>[];
      List? data = await _getBaseModel(_url + _selectAllDescription, params);
      if (data == null) {
        "没有获取到资源_selectAllDescription_${_url + _selectAllDescription}_${params.toString()}".print;
        return null;
      }
      data.forEach((element) {
        descriptionList.add(ResourcesDescriptionModel.fromJson(element));
      });
      return descriptionList;
    } catch (e) {
      "资源解析错误_selectAllDescription_${_url + _selectAllDescription}_${params.toString()}_${e.toString()}".print;
      return null;
    }
  }

  //获取后台的数据
  Future<T?> _getBaseModel<T>(String url, Map<String, dynamic> queryParameters,
      {String requestMethod = METHOD_GET, CancelToken? token}) async {
    try {
      var data = await requestApi(url, queryParameters, requestMethod: requestMethod, token: token);

      Map<String, dynamic> responseJson = json.decode(data);

      if (responseJson["code"] == null || responseJson["data"] == null) {
        "没有获取到正确数据_${url}_${queryParameters.toString()}_${requestMethod}______${responseJson.toString()}".print;
      } else if (responseJson["code"] == null || responseJson["code"] != CODE_SUCCESS) {
        "code：${url}_${queryParameters.toString()}_${requestMethod}______${responseJson.toString()}".print;
      } else if (responseJson["data"] == null || responseJson["data"].toString().length < 1) {
        "data：${url}_${queryParameters.toString()}_${requestMethod}______${responseJson.toString()}".print;
      } else {
        return responseJson["data"];
      }

      return null;
    } catch (e) {
      "获取我的后台资源-解析错误_${url}_${queryParameters.toString()}_${requestMethod}______${e.toString()}".print;
      "获取我的后台资源-解析错误_${url}_${queryParameters.toString()}_${requestMethod}______${e.toString()}".dialog;
      return null;
    }
  }
}
